define([
    'text!planmanage/addfileplan/templates/AddFilePlan_third.html',
    'planmanage/addfileplan/views/AddFilePlan_variable'
], function(AddFilePlanThirdViewTpl, VariableView) {
    // 主机配置gird
    var $destHostGrid;
    // 目标目录表达式配置gird
    var $targetXpathGrid;

    return fish.View.extend({
        template: fish.compile(AddFilePlanThirdViewTpl),
        i18nData: fish.extend({}),
        events: {
            'click #buttonDestFileAdd': 'buttonDestFileAdd',
            'click #buttonDestFileVerify': 'buttonDestFileVerify'
        },

        initialize: function() {
            // 验证并获取目标信息配置表单数据
            fish.on('getTargetFileFormData', $.proxy(this.getTargetFileFormData, this));
            // 目标数据表单数据回绑
            fish.on('setTargetFileForm', $.proxy(this.setTargetFileForm, this));
        },

        serialize: function() {
            return this.i18nData;
        },

        //这里用来初始化页面上要用到的fish组件
        afterRender: function() {
            var me = this;
            // 常用场景选择，选中事件
            $("input[name=dmBackupType]").click(function(){
                me.dmBackupTypeShow();
            });
            me.dmBackupTypeShow();

            // 源主机配置，下拉树
            var destHostId_setting = {
                async: {
                    enable: true,
                    contentType: "application/json",
                    url: webRoot + 'baseconfig/dmfileplan/getHostInfo.do',
                    type: 'post'
                },
                view: {
                    dblClickExpand:false,
                    selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: destHostIdonClick
                }
            };
            
            var destHostIdTree = $.fn.zTree.init($("#destHostId_tree"), destHostId_setting);
            var destHostIdTreeObj = $.fn.zTree.getZTreeObj("destHostId_tree");
            function destHostIdonClick(){
                nodes = destHostIdTree.getSelectedNodes();
                var nodeIdInput = $('input[name="destHostId"]');
                nodeIdInput.val(nodes[0].name);
                me.addDestHostGrid(nodes[0]);
                hidedestHostIdTree();
            };
            //下拉树相对位置，随着窗口联动
            function destHostIdTreePos(){
                var inputObj = $('input[name="destHostId"]');
                var inputObjOffSet = $('input[name="destHostId"]').offset();
                    var $treePs = $("#destHostId_commbox_tree").css({left:inputObjOffSet.left + "px", top: inputObj.outerHeight() + 40 + "px",width:inputObj.outerWidth() + "px",'z-index':9999});
                    return $treePs;
                    }
            $('input[name="destHostId"]').click(function(){
                destHostIdTreePos().slideDown("fast");
                $(window).resize(function(){
                    destHostIdTreePos();
                });
                $("body").bind("mousedown", onBodyDownNode);
            });
            function onBodyDownNode(event) {
                if (!(event.target.name == "destHostId" || event.target.id == "destHostId_commbox_tree" || $(event.target).parents("#destHostId_commbox_tree").length>0)) {
                    hidedestHostIdTree();
                }
            };
            function hidedestHostIdTree(){
                $("#destHostId_commbox_tree").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDownNode);
            };

            // 源目录表达式配置
            $('input[name="targetXpath"]').directory({
                dataTextField : "name",
                dataValueField : "value",
                addMenuWidth:120,
                value:[{type:'directory',value:'请配置目录：'}]
            });
        },

        dmBackupTypeShow: function(){
            switch ($("input[name=dmBackupType]:checked").attr("value")) {
            case "1":// 跨主机
                $("#destHost").show();
                if($destHostGrid == undefined){
                    $('#destHostGrid_div').removeClass("hidden");
                    return;
                }
                var rowNum = $destHostGrid.grid("getGridParam", "records");
                if(rowNum == 0){
                    $('#destHostGrid_div').addClass("hidden");
                    VariableView.setDestHost_OK(false);
                }else{
                    $('#destHostGrid_div').removeClass("hidden");
                    VariableView.setDestHost_OK(true);
                }
                break;
            case "0":// 同主机
                $("#destHost").hide();
                $('#destHostGrid_div').addClass("hidden");
                VariableView.setDestHost_OK(true);
                break;
            default:
                break;
            }
        },

        addDestHostGrid: function(addData){
            $('#destHostGrid_div').removeClass("hidden");
            // 主机配置 显示gird
            $destHostGrid = $("#destHost_grid").grid({
                height: 110,
                colModel: [{
                    name: 'hostId',
                    label: '主机ID',
                    sortable: false,
                    hidden: true,
                    key: true
                }, {
                    name: 'busiSys',
                    label: '域分组',
                    align: 'center',
                    sortable: false
                }, {
                    name: 'ip',
                    label: '主机IP',
                    align: 'center',
                    sortable: false
                }, {
                    name: 'hostName',
                    label: '主机名称',
                    align: 'center',
                    sortable: false
                }, {
                    name: '',
                    formatter: 'actions',
                    classes: 'text-primary',
                    width: 30,
                    sortable: false,
                    formatoptions: {
                        editbutton: false, //默认开启编辑功能
                        delbutton: true //默认开启删除功能
                    }
                }],
                afterDeleteRow: function (e, rowid, data, option) {
                    var rowNum = $destHostGrid.grid("getGridParam", "records");
                    if(rowNum == 0){
                        $('#destHostGrid_div').addClass("hidden");
                        VariableView.setDestHost_OK(false);
                        VariableView.setTargetXpath_OK(false);
                    }
                }
            });
            var rowNum = $destHostGrid.grid("getGridParam", "records");
            if(rowNum == 1){
                fish.toast('warn','目前只支持单个目标主机');
                return;
            }
            $destHostGrid.grid("addRowData", addData);
            VariableView.setDestHost_OK(true);
            VariableView.setTargetXpath_OK(false);
        },

        // 添加目标目录表达式
        buttonDestFileAdd: function(xpathStr){
            $('input[name="targetXpath"]').directory('value');

            if(xpathStr.type == "click"){
                xpathStr = $('input[name="targetXpath"]').val();
            }
            if($.parseJSON(xpathStr).length == 1){
                fish.toast('warn','请配置正确的目标目录表达式');
                return;
            }
            $('#targetXpathGrid_div').removeClass("hidden");
            // 主机配置 显示gird
            $targetXpathGrid = $("#targetXpath_grid").grid({
                height: 110,
                colModel: [{
                    name: 'xpathStr',
                    label: '目标目录表达式预览',
                    sortable: false,
                    formatter:function(cellval, opts, rwdat, _act){
                        var result = '';
                        var value = $.parseJSON(cellval);
                        for(var i = 1; i < value.length; i++){
                            var btnName = '';
                            if(value[i].type == 'list'){
                                if(value[i].value == 1){
                                    btnName = "本地网";
                                }else if(value[i].value == 5){
                                    btnName = "客户分组";
                                }else if(value[i].value == 6){
                                    btnName = "清单序列";
                                }else if(value[i].value == 7){
                                    btnName = "进程号";
                                }
                            }else if(value[i].type == 'timer'){
                                var btnValues = value[i].value.split(",");
                                if(btnValues[0] == '3'){// 年月日
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"天";
                                }else if(btnValues[0] == '2'){// 年月
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"个月";
                                }else if(btnValues[0] == '33'){// 年-月-日
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"天";
                                }else if(btnValues[0] == '22'){// 年-月
                                    btnName = "时间变量：偏移"+btnValues[1]+"-"+btnValues[2]+"个月";
                                }else{
                                    btnName = "时间变量";
                                }
                            }else if(value[i].type == '4'){
                                var btnValues = value[i].value.split(",");
                                btnName = "账期";
                                if(btnValues[0] != '账期'){
                                    btnName = "账期：偏移"+btnValues[0]+"-"+btnValues[1]+"个月";
                                }
                            }else{
                                btnName = value[i].value;
                            }
                            result += '<button type="button" class="btn btn-default ui-filenamegrid-btn">'+btnName+'</button>';
                        }
                        return result;
                    }
                }, {
                    name: '',
                    formatter: 'actions',
                    classes: 'text-primary',
                    width: 10,
                    sortable: false,
                    formatoptions: {
                        editbutton: false, //默认开启编辑功能
                        delbutton: true //默认开启删除功能
                    }
                }],
                afterDeleteRow: function (e, rowid, data, option) {
                    var rowNum = $targetXpathGrid.grid("getGridParam", "records");
                    if(rowNum == 0){
                        $('#targetXpathGrid_div').addClass("hidden");
                    }
                    VariableView.setTargetXpath_OK(false);
                }
            });
            var newData = {"xpathStr": xpathStr};
            $targetXpathGrid.grid("addRowData", newData);

            VariableView.setTargetXpath_OK(false);
        },

        // 目标目录表达式验证 按钮点击事件
        buttonDestFileVerify: function(){
            if(!$targetXpathGrid || $targetXpathGrid.grid("getRowData").length == 0){                
                $('textarea[name="targetXpath_show"]').val('');
                fish.toast('warn','请配置目标目录表达式');
            }else{
                var targetXpathGridData = $targetXpathGrid.grid("getRowData");
                var data = VariableView.getPlanFormData();
                data.sourceXpathGridDataStr = this.getGridDataStr(2, $targetXpathGrid.grid("getRowData"));
                fish.ajax({
                    async : false,
                    url: ctx + '/baseconfig/dmfileplan/xpathVerify.do',
                    showMask: false,  //是否自动显式全局遮罩
                    showError: true, //在出现异常时自动显示异常信息，后台需要返回的数据格式：{code:'ERROR-1001',message:'登录失败'}
                    timeout: 30000,   //超过3秒显式全局遮罩，此参数在showMask为true时才有效
                    data: data,
                    beforeSend: function(){
                        $.blockUI({message : "目标目录表达式验证中,请稍候..."});
                    },
                    complete: function(xhr, status){
                        $.unblockUI();
                        if(status == 'timeout'){
                            fish.toast('error', "网络请求超时");
                            return;
                        }
                        $('textarea[name="targetXpath_show"]').val('');
                        var xpath = "";
                        var xpathList = xhr.responseJSON.xpathList;
                        for(var i = 0; i < xpathList.length; i++){
                            xpath += xpathList[i]+"\n";
                        }
                        if(xhr.responseJSON.xpathIsOK){// 验证通过
                            VariableView.setTargetXpath_OK(true);
                        }else{
                            xpath = "ERROR:\n" + xpath;
                            VariableView.setTargetXpath_OK(false);
                        }
                        $('textarea[name="targetXpath_show"]').val(xpath);
                    },
                    //【注意】如果你在这里配置了自己的error处理函数，fish.ajax就不会自动帮你显示异常信息了！
                    error:function(){
                        $.unblockUI();
                    }
                });
            }
        },

        // 获取目标数据配置表单数据
        getTargetFileFormData: function(){
            var targetFileFormData = $("#targetFileForm").form("value");
            // 判断源目录表达式配置预览是否成功
            if(!VariableView.getTargetXpath_OK()){
                fish.toast('warn','目标目录表达式配置未验证或验证不通过，请点击“结果预览”按钮进行验证');
                VariableView.setTargetFileForm_OK(false);
            }else{
                if(targetFileFormData.dmBackupType == '1'){// 跨主机备份模式
                    // 目标主机配置
                    if(!$destHostGrid || !VariableView.getDestHost_OK()){
                        fish.toast('warn','请选择目标主机');
                        VariableView.setDestHost_OK(false);
                        VariableView.setTargetFileForm_OK(false);
                    }else{
                        targetFileFormData.destHostGridDataStr = this.getGridDataStr(1, $destHostGrid.grid("getRowData"));
                        // 目标目录表达式配置
                        if(!$targetXpathGrid){
                            fish.toast('warn','请配置目标目录表达式');
                            VariableView.setTargetFileForm_OK(false);
                        }else{
                            targetFileFormData.targetXpathGridDataStr = this.getGridDataStr(2, $targetXpathGrid.grid("getRowData"));
                            // 验证源和目标目录表达式个数是否一致，或者目标目录只有一个
                            var targetXpathNum = $.parseJSON(targetFileFormData.targetXpathGridDataStr).length;
                            var sourceXpathNum = $.parseJSON(VariableView.getSrcFileFormData().sourceXpathGridDataStr).length;
                            if(targetXpathNum != sourceXpathNum){
                                if(targetXpathNum != 1){
                                    fish.toast('warn','源与目标目录个数需一致或者只有一个目标目录，请重新配置');
                                    VariableView.setTargetFileForm_OK(false);
                                }else{
                                    VariableView.setTargetFileFormData(targetFileFormData);
                                    VariableView.setTargetFileForm_OK(true);
                                }
                            }else{
                                VariableView.setTargetFileFormData(targetFileFormData);
                                VariableView.setTargetFileForm_OK(true);
                            }
                        }
                    }
                }else{// 同主机备份模式
                    // 目标目录表达式配置
                    if(!$targetXpathGrid){
                        fish.toast('warn','请配置目标目录表达式');
                        VariableView.setTargetFileForm_OK(false);
                    }else{
                        targetFileFormData.targetXpathGridDataStr = this.getGridDataStr(2, $targetXpathGrid.grid("getRowData"));
                        // 验证源和目标目录表达式个数是否一致，或者目标目录只有一个
                        var targetXpathNum = $.parseJSON(targetFileFormData.targetXpathGridDataStr).length;
                        var sourceXpathNum = $.parseJSON(VariableView.getSrcFileFormData().sourceXpathGridDataStr).length;
                        if(targetXpathNum != sourceXpathNum){
                            if(targetXpathNum != 1){
                                fish.toast('warn','源与目标目录个数需一致或者只有一个目标目录，请重新配置');
                                VariableView.setTargetFileForm_OK(false);
                            }else{
                                VariableView.setTargetFileFormData(targetFileFormData);
                                VariableView.setTargetFileForm_OK(true);
                            }
                        }else{
                            VariableView.setTargetFileFormData(targetFileFormData);
                            VariableView.setTargetFileForm_OK(true);
                        }
                    }
                }
            }
        },

        // 获取有用的gridData，并转成String
        getGridDataStr: function(type, gridData){
            var newGridData = [];
            for(var i = 0; i < gridData.length; i++){
                var oneData = {};
                if(type == 1){
                    oneData.hostId = gridData[i].hostId;
                    oneData.ip = gridData[i].ip;
                }else if(type == 2){
                    oneData.xpathStr = gridData[i].xpathStr;
                }
                newGridData.push(oneData);
            }
            return JSON.stringify(newGridData);
        },

        // 目标数据表单数据回绑
        setTargetFileForm: function(){
            var data = VariableView.getDmStrategyInfo();
            // 常用场景选择
            var dmBackupType = data.dmBackupType;
            $("input[name='dmBackupType'][value="+dmBackupType+"]").attr("checked",true);
            this.dmBackupTypeShow();
            if(dmBackupType == 1){// 跨主机
                // 目标主机
                this.addDestHostGrid($.parseJSON(data.destHostGridDataStr));
            }
            // 目标目录表达式
            for(var i = 0; i < data.targetXpathGridData.length; i++){
                this.buttonDestFileAdd(data.targetXpathGridData[i].xpathStr);
            }
            VariableView.setTargetXpath_OK(true);
        }
    });
});